/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package deti.es.persistence.calendar;

import deti.es.persistence.account.AccountDoesNotExist;
import deti.es.ukni.persistence.entity.Band;
import deti.es.ukni.persistence.entity.Event;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
 * Implementation of the {@link CalendarManagerRemote} interface.
 *
 * @author ukni
 */
@Stateless( mappedName="ejb/MyBandCalendarManager" )
public class CalendarManagerBean implements CalendarManagerRemote{

    @PersistenceContext
    private EntityManager manager;

    public CalendarManagerBean() { }

    /**
    *  Implementation of (@link CalendarManagerRemote#createEvent)
    */
    public Event createEvent(Band banda, Date eventdate, String location, double latitude,
                                 double longitude) {


        Event newEvent = new Event();

        newEvent.setLocation(location);
        newEvent.setLatitude(latitude);
        newEvent.setLongitude(longitude);
        newEvent.setEventdate(eventdate);

        newEvent.setDatecreation(new java.util.Date() );

        manager.persist(newEvent);

        
        banda.getEventCollection().add(newEvent);
        manager.merge(banda);

        return newEvent;
    }

    /**
    *  Implementation of (@link CalendarManagerRemote#findBandEvents)
    */
    public Set<Event> findBandEvents(Integer IDBand) throws AccountDoesNotExist {

        try{
            Band band = manager.find(Band.class, IDBand);
            return band.getEventCollection();
        } catch( NoResultException e ){
            throw new AccountDoesNotExist( IDBand.toString() );
        }
    }

    /**
    *  Implementation of (@link CalendarManagerRemote#findAllEvents)
    */
    public List<Event> findAllEvents() {
        return manager.createQuery("select object  from Event as o").getResultList();
    }

    /**
    *  Implementation of (@link CalendarManagerRemote#findBandEvent)
    */
    public Event findBandEvent(Integer IDEvent) throws EventDoesNotExist {
        Query q =  manager.createQuery("select e from Event as e where e.idevent = :idevent");
        q.setParameter("idevent", IDEvent);

        try{
            Event event = (Event) q.getSingleResult();
            return event;
        } catch( NoResultException e ){
            throw new EventDoesNotExist( IDEvent );
        }
    }

}